package com.gem.growingtree.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.gem.growingtree.dao.AdminDao;
import com.gem.growingtree.db.DBLink;
import com.gem.growingtree.model.Admin;

public class AdminService implements AdminDao {
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	@Override
	public boolean check(Admin admin) throws Exception {
		boolean flag = false;
		conn = DBLink.getConnection();
		String sql = "select userId,userName,pass from users where userName=? and pass=?";
		pstmt = conn.prepareStatement(sql);		
		pstmt.setString(1, admin.getAdminName());
		pstmt.setString(2, admin.getAdminPass());
		rs = pstmt.executeQuery();
		if(rs.next()){
			flag = true;
		}
		close();
		return flag;
	}

	@Override
	public boolean register(Admin admin) throws Exception {
		boolean flag = false;
		conn = DBLink.getConnection();
		System.out.println("----->"+admin.getAdminName()+"-----");
		String sql = "insert into users(userId,userName,pass,identity) values(default,?,?,3)";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1,admin.getAdminName());
		pstmt.setString(2,admin.getAdminPass());
		int rows = pstmt.executeUpdate();
		if(rows == 1){
			flag = true;
		}
		close();
		return flag;
	}
	public void close(){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(pstmt != null){
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}